<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html,
      body {
        height: 100%;
      }
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        border: 1px solid black;
        margin: 0 auto;
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas width="500" height="500">浏览器版本过低</canvas>
    <script>
      // 获取画布
      const canvas = document.querySelector('canvas');
      // 获取画笔
      const c = canvas.getContext('2d');
      const w = 500;
      const h = 500;
      function r(num) {
        return Math.random() * num;
      }
      class Ball {
        constructor() {
          this.x = r(3) + 60; // [0,500)
          this.y = r(2) + 60; // [0,500)
          this.r = r(40) + 20; // [20,60)
          this.xSpeed = r(4) + 1; // [1,5)
          this.ySpeed = r(4) + 1; //[1,5)
          this.color = '#' + parseInt(Math.random() * 0xffffff).toString(16);
        }

        show() {
          c.beginPath();
          c.arc(this.x, this.y, this.r, 0, Math.PI * 2);
          c.fillStyle = this.color;
          c.fill();
        }

        run() {
          if (this.x - this.r <= 0 || this.x + this.r >= w) {
            this.xSpeed = -this.xSpeed;
          }
          if (this.y - this.r <= 0 || this.y + this.r >= h) {
            this.ySpeed = -this.ySpeed;
          }
          this.x += this.xSpeed;
          this.y += this.ySpeed;
          this.show();
        }
      }
      const ball_list = [];
      for (let i = 0; i < 50; i++) {
        const obj_Ball = new Ball();
        ball_list.push(obj_Ball);
      }

      setInterval(() => {
        c.clearRect(0, 0, w, h);
        ball_list.forEach((item, key) => {
          item.run();
        });
      }, 10);
    </script>
  </body>
</html>
